//
//  CXLEmotionView.swift
//  Emotion
//
//  Created by 曹晓龙 on 15/10/23.
//  Copyright © 2015年 曹晓龙. All rights reserved.
//

import UIKit

/// 重用标示
private let CXLEmotionViewCellID = "CXLEmotionViewCellID"

/// 自定义表情视图
class CXLEmotionView: UIView {
    
    var backCallBlock:(emoticon:CXLEmoticon)->()
    
    /// 存放所有的表情图片模型的数组
    private let emoticonGroups = CXLEmoticonManager.shareEmoticionManager.emoticonGroups
    
    //MARK: - 监听方法
    @objc private func clickItem(item:UIBarButtonItem){

        let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
        
        collectionVM.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
    }
    
    init(backCallBlock:(emoticon:CXLEmoticon)->()){
        
        self.backCallBlock = backCallBlock
        
        var rect = UIScreen.mainScreen().bounds
        
        rect.size.height = 226
        
        super.init(frame: rect)
        
        setupUI()
        
        ///  界面布局完成后,默认选中默认表情项
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            
            let indexPath = NSIndexPath(forItem: 0, inSection: 1)
            self.collectionVM.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        }
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //MARK: - 懒加载
    //表情主题视图
    private lazy var collectionVM:UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: CXLCollectionViewLayout())
    
    /// 工具条
    private lazy var toolBar:UIToolbar = UIToolbar()
    
    //MARK: -自定义流水布局
    /// 类中类,自定义layout
    class CXLCollectionViewLayout:UICollectionViewFlowLayout {
        
        override func prepareLayout() {

            let row :CGFloat = 3
            
            let col :CGFloat = 7
            
            let width:CGFloat = collectionView!.bounds.width / col
            
            let layoutMargin = (collectionView!.bounds.height - row * width ) * 0.499
            
            itemSize = CGSize(width: width, height: width)
            
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            
            sectionInset = UIEdgeInsets(top: layoutMargin, left: 0, bottom: layoutMargin, right: 0)
            
            scrollDirection = UICollectionViewScrollDirection.Horizontal
            
            collectionView?.showsHorizontalScrollIndicator = false
            
            collectionView?.pagingEnabled = true
            
            collectionView?.bounces = false
        }
        
    }
}

// MARK: - 设置UI
private extension CXLEmotionView {
    
    ///  设置UI界面
    func setupUI(){
        
        // 添加控键
        addSubview(collectionVM)
        addSubview(toolBar)
        
        //自动布局
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
            make.bottom.equalTo(self.snp_bottom)
            make.height.equalTo(44)
        }
        
        collectionVM.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_top)
            make.bottom.equalTo(toolBar.snp_top)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
        }
        
        prepareToolBar()
        prepareCollectionVM()
    }
    
    ///  准备toolbar
    private func prepareToolBar(){
        
        var items = [UIBarButtonItem]()
        
        var index = 0
        
        for s in emoticonGroups {
            
            items.append(UIBarButtonItem(title: s.group_name_cn, style: UIBarButtonItemStyle.Plain, target: self, action: "clickItem:"))
            
            items.last?.tag = index
            
            index++
            
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        
        items.removeLast()
        
        toolBar.items = items
        
        toolBar.tintColor = UIColor.darkGrayColor()
    }
    
    ///  准备表情collectionView
    private func prepareCollectionVM(){
        
        collectionVM.registerClass(CXLCollectionVMCell.self, forCellWithReuseIdentifier: CXLEmotionViewCellID)
        
        collectionVM.backgroundColor = UIColor(white: 0.85, alpha: 1.0)
        
        collectionVM.dataSource = self
        
        collectionVM.delegate = self
    }
}

// MARK: - 数据源方法
extension CXLEmotionView:UICollectionViewDataSource, UICollectionViewDelegate {
    
    ///  选中某个cell
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let emoticon = emoticonGroups[indexPath.section].emoticons[indexPath.row]
        
        backCallBlock(emoticon: emoticon)
        
        if indexPath.section > 0 { // 常用分组不参与排序
            
            CXLEmoticonManager.shareEmoticionManager.addFavouriteEmoticon(emoticon)
        }
        
    }
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        
        return emoticonGroups.count
        
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return emoticonGroups[section].emoticons.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CXLEmotionViewCellID, forIndexPath: indexPath) as! CXLCollectionVMCell
        
        cell.emoticon = emoticonGroups[indexPath.section].emoticons[indexPath.item]
        
        return cell
    }
}

//MARK: -自定义表情Cell
class CXLCollectionVMCell:UICollectionViewCell {
    
    
    private var emoticon:CXLEmoticon?{
        
        didSet{
            
            emoticionBtn.setImage(UIImage(named: emoticon!.pngPath), forState: UIControlState.Normal)
            
            emoticionBtn.setTitle(emoticon?.emoji, forState: UIControlState.Normal)
            
            if emoticon!.isRemoveBtn {
                emoticionBtn.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
            }
        }
    }
    
    //MARK: - 构造函数
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
    
        
        contentView.addSubview(emoticionBtn)
        
        emoticionBtn.titleLabel?.font = UIFont.systemFontOfSize(32)
        
        emoticionBtn.backgroundColor = UIColor.whiteColor()
        emoticionBtn.userInteractionEnabled = false
        emoticionBtn.frame = CGRectInset(bounds, 4, 4)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: -懒加载
    /// 每个表情的cell
    private lazy var emoticionBtn:UIButton = UIButton()
}